import { gameConfig } from './config.js';
import { updateBestTime, loadRecords, getBestTime } from './records.js';
import { addCustomPairs, getCustomPairs, loadCustomWords } from './custom-words.js';

// 加载保存的记录和自定义词对
loadRecords();
loadCustomWords();

let gameTimer;
let seconds = 0;
let matches = 0;
let flippedCards = [];
let currentMode = null;
let currentPairs = [];

// 获取DOM元素
const modeCards = document.querySelectorAll('.mode-card');
const customMode = document.querySelector('.custom-mode');
const gameContainer = document.querySelector('.game-container');
const cardGrid = document.querySelector('.card-grid');
const timerDisplay = document.getElementById('timer');
const matchesDisplay = document.getElementById('matches');
const startCustomGameBtn = document.getElementById('startCustomGame');
const restartGameBtn = document.getElementById('restartGame');
const customTextarea = document.querySelector('.custom-mode textarea');

// 添加模式选择事件监听器
modeCards.forEach(card => {
    card.addEventListener('click', () => {
        const mode = card.dataset.mode;
        if (mode === 'custom') {
            showCustomMode();
        } else {
            startGame(mode);
        }
    });
});

// 显示自定义模式输入界面
function showCustomMode() {
    customMode.style.display = 'block';
    gameContainer.style.display = 'none';
}

// 开始游戏
function startGame(mode, customPairs = null) {
    currentMode = mode;
    if (mode === 'custom') {
        currentPairs = customPairs || getCustomPairs();
    } else {
        currentPairs = gameConfig.wordPairs[mode].slice(0, gameConfig.pairCounts[mode]);
    }
    
    // 更新总配对数显示
    document.getElementById('totalPairs').textContent = currentPairs.length;
    // 更新最快记录显示
    const bestTime = getBestTime(mode);
    document.getElementById('bestTime').textContent = bestTime === Infinity ? '-' : bestTime;
    
    // 重置游戏状态
    resetGame();
    
    // 创建卡片
    createCards();
    
    // 显示游戏界面
    customMode.style.display = 'none';
    gameContainer.style.display = 'block';
    
    // 开始计时
    startTimer();
}

// 重置游戏状态
function resetGame() {
    clearInterval(gameTimer);
    seconds = 0;
    matches = 0;
    flippedCards = [];
    timerDisplay.textContent = '0';
    matchesDisplay.textContent = '0';
    cardGrid.innerHTML = '';
}

// 创建卡片
function createCards() {
    // 创建卡片数组（包含中英文）
    const cards = [...currentPairs.map(pair => pair[0]), ...currentPairs.map(pair => pair[1])];
    
    // 随机打乱卡片
    for (let i = cards.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [cards[i], cards[j]] = [cards[j], cards[i]];
    }
    
    // 创建卡片元素
    cards.forEach(text => {
        const card = document.createElement('div');
        card.className = 'card';
        card.dataset.value = text;
        card.addEventListener('click', () => flipCard(card));
        cardGrid.appendChild(card);
    });
}

// 翻转卡片
function flipCard(card) {
    // 如果卡片已经匹配或已经翻开，则不执行操作
    if (card.classList.contains('matched') || card.classList.contains('flipped') || flippedCards.length >= 2) {
        return;
    }
    
    // 翻转卡片
    card.classList.add('flipped');
    card.textContent = card.dataset.value;
    flippedCards.push(card);
    
    // 检查是否有两张卡片被翻开
    if (flippedCards.length === 2) {
        checkMatch();
    }
}

// 检查匹配
function checkMatch() {
    const [card1, card2] = flippedCards;
    const value1 = card1.dataset.value;
    const value2 = card2.dataset.value;
    
    // 检查是否匹配（在词对中查找）
    const isMatch = currentPairs.some(pair => 
        (pair[0] === value1 && pair[1] === value2) || 
        (pair[1] === value1 && pair[0] === value2)
    );
    
    setTimeout(() => {
        if (isMatch) {
            // 匹配成功
            card1.classList.add('matched');
            card2.classList.add('matched');
            matches++;
            matchesDisplay.textContent = matches;
            
            // 检查游戏是否完成
            if (matches === currentPairs.length) {
                clearInterval(gameTimer);
                const isNewRecord = updateBestTime(currentMode, seconds);
                setTimeout(() => {
                    const bestTime = getBestTime(currentMode);
                    const message = isNewRecord
                        ? `恭喜！你创造了新纪录！用时 ${seconds} 秒完成了游戏！`
                        : `恭喜！你用时 ${seconds} 秒完成了游戏！\n当前最快记录：${bestTime} 秒`;
                    alert(message);
                }, 300);
            }
        } else {
            // 匹配失败，翻回卡片
            card1.classList.remove('flipped');
            card2.classList.remove('flipped');
            card1.textContent = '';
            card2.textContent = '';
        }
        
        flippedCards = [];
    }, 1000);
}

// 开始计时器
function startTimer() {
    gameTimer = setInterval(() => {
        seconds++;
        timerDisplay.textContent = seconds;
    }, 1000);
}

// 自定义模式开始游戏按钮事件
startCustomGameBtn.addEventListener('click', () => {
    const input = customTextarea.value.trim();
    const pairs = input.split('\n')
        .map(line => line.trim())
        .filter(line => line)
        .map(line => line.split(/\s+/));
    
    if (pairs.length < 4) {
        alert('请至少输入4对中英文对应词！');
        return;
    }
    
    if (pairs.some(pair => pair.length !== 2)) {
        alert('格式错误！请确保每行包含一个中文和一个英文，用空格分隔。');
        return;
    }
    
    addCustomPairs(pairs);
startGame('custom', pairs.slice(0, gameConfig.pairCounts.custom));
});

// 重新开始按钮事件
restartGameBtn.addEventListener('click', () => {
    if (currentMode) {
        startGame(currentMode, currentMode === 'custom' ? currentPairs : null);
    }
});